import { ReactElement, useState, useEffect } from 'react'
import { Radio, Input, Table, Space, Button, Modal } from 'antd'
import style from './index.module.less'
import { PerformanceSchema } from '@components/schema/performanceSchema'
import { getListRequest, DataSchema, refreshListRequest } from './ajax'
import { awaitWrap } from '@js/tool'
import { getColumn } from './util'
import EditModal from './components/editModal'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { json2Excel } from '@js/excel'

const { confirm } = Modal

// 初始化列表
async function initList (id: string, setList: (v: DataSchema[]) => void, setLoading: (v: boolean) => void): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(getListRequest(id))
  setLoading(false)
  if (e === null && d instanceof Array) {
    setList(d)
  }
}

// 刷新绩效
async function refreshScore (id: string, setList: (v: DataSchema[]) => void, setLoading: (v: boolean) => void): Promise<void> {
  setLoading(true)
  const [e, d] = await awaitWrap(refreshListRequest(id))
  setLoading(false)
  if (e === null && d instanceof Array) {
    setList(d)
  }
}

// 下载excel二次确认
function confirmDownload (list: DataSchema[], title: string): void {
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: '您确定要导出excel吗？',
    onOk () {
      downloadExcel(list, title)
    }
  })
}

function downloadExcel (list: DataSchema[], title: string): void {
  const r: Array<{ data: Array<{ [k: string]: any }>, sheetname: string }> = []
  r.push({ data: expendAccepterDataToExcel(list.filter(li => li.employee_type === 'accepter')), sheetname: '受理秘书' })
  r.push({ data: expendProcesserDataToExcel(list.filter(li => li.employee_type === 'processer')), sheetname: '办案秘书' })
  r.push({ data: expendManagerDataToExcel(list.filter(li => li.employee_type === 'manager')), sheetname: '非办案人员' })
  json2Excel(r, title)
}

function expendAccepterDataToExcel (list: DataSchema[]): Array<{ [k: string]: any }> {
  return list.map((li, i) => {
    const o: { [k: string]: any } = {
      序号: i + 1,
      姓名: li.name,
      受理权重: typeof li.accepter_case_weights === 'number' ? li.accepter_case_weights.toFixed(2) : '',
      受理分值: typeof li.accepter_case_score === 'number' ? li.accepter_case_score.toFixed(2) : '',
      受理均值分: typeof li.accepter_ratio_score === 'number' ? li.accepter_ratio_score.toFixed(2) : '',
      咨询次数: typeof li.accepter_advise_count === 'number' ? li.accepter_advise_count.toFixed(2) : '',
      工作表现: typeof li.accepter_case_coefficient === 'number' ? li.accepter_case_coefficient.toFixed(2) : '',
      办案权重: typeof li.processer_case_weights === 'number' ? li.processer_case_weights.toFixed(2) : '',
      办案分值: typeof li.processer_case_score === 'number' ? li.processer_case_score.toFixed(2) : '',
      办案均值分: typeof li.processer_ratio_score === 'number' ? li.processer_ratio_score.toFixed(2) : '',
      '撤裁/不予执行次数': typeof li.dismissal_count === 'number' ? li.dismissal_count.toFixed(2) : '',
      非办案权重: typeof li.work_weights === 'number' ? li.work_weights.toFixed(2) : '',
      非办案分值: typeof li.work_score === 'number' ? li.work_score.toFixed(2) : '',
      总分: typeof li.score === 'number' ? li.score.toFixed(2) : '',
      除同期均值后总分: typeof li.score_withratio === 'number' ? li.score_withratio.toFixed(2) : ''
    }
    return o
  })
}

function expendProcesserDataToExcel (list: DataSchema[]): Array<{ [k: string]: any }> {
  return list.map((li, i) => {
    const o: { [k: string]: any } = {
      序号: i + 1,
      姓名: li.name,
      办案权重: typeof li.processer_case_weights === 'number' ? li.processer_case_weights.toFixed(2) : '',
      办案分值: typeof li.processer_case_score === 'number' ? li.processer_case_score.toFixed(2) : '',
      办案均值分: typeof li.processer_ratio_score === 'number' ? li.processer_ratio_score.toFixed(2) : '',
      '撤裁/不予执行次数': typeof li.dismissal_count === 'number' ? li.dismissal_count.toFixed(2) : '',
      非办案权重: typeof li.work_weights === 'number' ? li.work_weights.toFixed(2) : '',
      非办案分值: typeof li.work_score === 'number' ? li.work_score.toFixed(2) : '',
      总分: typeof li.score === 'number' ? li.score.toFixed(2) : '',
      除同期均值后总分: typeof li.score_withratio === 'number' ? li.score_withratio.toFixed(2) : ''
    }
    return o
  })
}

function expendManagerDataToExcel (list: DataSchema[]): Array<{ [k: string]: any }> {
  return list.map((li, i) => {
    const o: { [k: string]: any } = {
      序号: i + 1,
      姓名: li.name,
      办案权重: typeof li.processer_case_weights === 'number' ? li.processer_case_weights.toFixed(2) : '',
      办案分值: typeof li.processer_case_score === 'number' ? li.processer_case_score.toFixed(2) : '',
      办案均值分: typeof li.processer_ratio_score === 'number' ? li.processer_ratio_score.toFixed(2) : '',
      '撤裁/不予执行次数': typeof li.dismissal_count === 'number' ? li.dismissal_count.toFixed(2) : '',
      非办案权重: typeof li.work_weights === 'number' ? li.work_weights.toFixed(2) : '',
      非办案分值: typeof li.work_score === 'number' ? li.work_score.toFixed(2) : '',
      总分: typeof li.score === 'number' ? li.score.toFixed(2) : ''
    }
    return o
  })
}

interface Props {
  data: PerformanceSchema | null
}

function Main ({ data }: Props): ReactElement {
  const [name, setName] = useState('')
  const [pType, setPType] = useState<'accepter' | 'processer' | 'manager'>('accepter')
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState<DataSchema[]>([])
  const [dataSource, setDataSource] = useState<DataSchema[]>([])
  const [visible, setVisible] = useState(false)
  const [modifyData, setModifyData] = useState<DataSchema | null>(null)
  function refreshData (): void {
    if (data !== null) {
      refreshScore(data.id, setList, setLoading).catch(e => console.error(e))
    }
  }
  useEffect(() => {
    if (data !== null) {
      initList(data.id, setList, setLoading).catch(e => console.error(e))
    }
  }, [data])
  useEffect(() => {
    setDataSource(list.filter(li => {
      if (li.employee_type !== pType) {
        return false
      }
      if (name !== '' && !li.name.includes(name)) {
        return false
      }
      return true
    }).map((li: DataSchema, i: number) => {
      li.orderno = i + 1
      return li
    }))
  }, [list, pType, name])
  return (
    <div className={style.container}>
      <EditModal visible={visible} data={modifyData} pType={pType} hide={() => { setModifyData(null); setVisible(false) }} refreshData={refreshData} />
      <div className={style['operate-line']}>
        <Radio.Group value={pType} onChange={e => setPType(e.target.value)}>
          <Radio.Button value='accepter'>受理秘书</Radio.Button>
          <Radio.Button value='processer'>办案秘书</Radio.Button>
          <Radio.Button value='manager'>非办案人员</Radio.Button>
        </Radio.Group>
        <Space size={12}>
          <Button type='primary' ghost onClick={() => confirmDownload(list, data === null ? '' : data?.title)}>导出excel</Button>
          <Button type='primary' onClick={() => refreshData()}>刷新绩效</Button>
          <span className={style.search}>
            <span className={style['search-label']}>名称：</span>
            <Input.Search placeholder='请输入' value={name} onChange={e => setName(e.target.value)} />
          </span>
        </Space>
      </div>
      <Table rowKey='id' dataSource={dataSource} loading={loading} columns={getColumn(pType, setVisible, setModifyData)} pagination={false} />
    </div>
  )
}

export default Main
